<?php

namespace addons\qingdongams\model;

use think\Db;
use think\Model;
use traits\model\SoftDelete;

/**
 *区域管理
 */
class AreaManagement extends Model
{
    use SoftDelete;


    // 表名,不含前缀
    protected $name = 'qingdongams_area_management';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';
    // 追加属性
    protected $append = [
        'province_text',
    ];

    /**
     * 获取地址对应 区域
     * @param $address
     * @return array|void
     */
    public static function whereAddressProvince($address)
    {
        $area = explode('省', $address);
        if (empty($area)) {
            return [];
        }
        if (count($area) == 1) {
            $area = explode('区', $address);
        }
        $province = AreaProvince::where(['name' => ['like', "%{$area[0]}%"]])->find();
        if (empty($province)) {
            return [];
        }
        $where[] = ['exp', Db::raw('FIND_IN_SET(' . $province['id'] . ',province_ids)')];
        $management = self::where($where)->find();
        return $management ?? [];
    }

    public static function addAreaManagement($params)
    {
        $model = new self();
        $model->save($params);
        $lastId = $model->getLastInsID();
        $staff_rule = [
            'type' => 'data',
            'pid' => 784,
            'title' => $params['name'],
            'name' => $lastId
        ];
        StaffRule::create($staff_rule);
        return true;
    }

    public function getProvinceTextAttr($value, $data)
    {
        $ids = explode(',', $data['province_ids'] ?? '');
        $list = AreaProvince::where('id', 'in', $ids)->column('name');
        if ($list) {
            return implode(',', $list);
        }
        return '';
    }

    //添加区域

    public function getCreatetimeAttr($value)
    {
        if ($value) {
            return date('Y-m-d H:i', $value);
        }

        return $value;
    }
}
